package com.xx.library.controller;

import com.xx.library.common.Result;
import com.xx.library.dto.BorrowRequest;
import com.xx.library.entity.BorrowRecord;
import com.xx.library.entity.User;
import com.xx.library.service.BorrowRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/api/borrows")
public class BorrowRecordController {

    @Autowired
    private BorrowRecordService borrowRecordService;

    // 根据ID查询借阅记录
    @GetMapping("/{id}")
    public Result<BorrowRecord> getBorrowRecordById(@PathVariable Long id) {
        return Result.success(borrowRecordService.getBorrowRecordById(id));
    }

    // 根据当前登陆用户ID查询借阅记录
    @GetMapping("/user")
    public Result<List<BorrowRecord>> getBorrowRecordsByUserId(HttpSession httpSession) {
        User user = (User) httpSession.getAttribute("user");
        Long userId = user.getId();
        return Result.success(borrowRecordService.getBorrowRecordsByUserId(userId));
    }

    // 根据图书ID查询借阅记录
    @GetMapping("/book/{bookId}")
    public Result<List<BorrowRecord>> getBorrowRecordsByBookId(@PathVariable Long bookId) {
        return Result.success(borrowRecordService.getBorrowRecordsByBookId(bookId));
    }


    //  查询所有逾期借阅
    @GetMapping("/overdue")
    public Result<List<BorrowRecord>> getOverdueRecords() {
        return Result.success(borrowRecordService.getOverdueRecords());
    }

    @GetMapping("/search")
    public Result<List<BorrowRecord>> searchBorrowRecords(BorrowRecord borrowRecord) {
        return Result.success(borrowRecordService.getBorrowRecordsByCondition(borrowRecord));
    }

    // 借书
    @PostMapping("/borrow")
    public Result<Void> borrowBook(@RequestBody BorrowRequest request, HttpSession session) {
        // 从session中获取用户信息
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error("请先登录");
        }
        borrowRecordService.borrowBook(user.getId(), request.getBookId());
        return Result.success();
    }

    // 还书
    @PostMapping("/{id}/return")
    public Result<Void> returnBook(@PathVariable Long id) {
        borrowRecordService.returnBook(id);
        return Result.success();
    }

    // 续借图书
    @PostMapping("/{id}/renew")
    public Result<Void> renewBook(@PathVariable Long id) {
        borrowRecordService.renewBook(id);
        return Result.success();
    }
} 